/**
 * @author Stephan Pfaff (http://www.derdaumen.net)
 */

/**
 * ItemContainer Klasse
 * @param type 				String - Typ des ItemContainers (preface, category, project oder button)
 * @param prefix 			String - Prefix der MySQL Datensätze die mit dem Containertyp verknüpft sind (ctg, prj oder btn)
 * @param urlLoad 			String - URL des php Script welches die Inhalte des Containers aus der Datenbank lädt
 * @param urlSave 			String - URL des php Script welches die Inhalte des Containers in die Datenbank speichert
 * @param urlNew 			String - URL des php Script welches die ein neues Objekt in der Datenbank anlegt
 * @param urlDelete			String - URL des php Script welches das aktuelle Objekt in der Datenbank löscht
 * @param urlDeleteThumb	String - URL des php Script welches das Thumbnail des aktuelle Objekts in der Datenbank und auf dem Datenträger löscht
 * @param urlDeleteImage	String - URL des php Script welches das Bild des aktuelle Objekts in der Datenbank und auf dem Datenträger löscht
 */
function ItemContainer(type, prefix, urlLoad, urlSave, urlNew, urlDelete, urlDeleteThumb, urlDeleteImage ) {
	try {
		this.type = type;
		this.prefix = prefix;
		this.item_selector = '#select_'+type;
		this.position_selector = '#'+prefix+'_position';
		this.form = '#form_'+type;
		this.urlLoad = urlLoad;
		this.urlSave = urlSave;
		this.urlNew = urlNew;
		this.urlDelete = urlDelete;
		this.urlDeleteThumb = urlDeleteThumb;
		this.urlDeleteImage = urlDeleteImage;
		this.items = null;
		var handle = this;
		/*
		 * #########################################################################
		 * ########################### Thumb Uploader ##############################
		 * #########################################################################
		 */
		this.progressBarThumb = $('#'+this.prefix+'_thumb_upload_progress_bar').progressbar({});
		this.thumbUploader = $('#'+this.prefix+'_thumb_upload_container').swfupload({
			upload_url: libPathPHP+"uploadThumbToCrop.php",
			file_size_limit : maxImgSize,
			file_types : "*.jpg;*.png;*.gif;*.jpeg",
			file_types_description : "Web Image Files",
			file_upload_limit : "0",
			flash_url : libPathJS+"plugins/swfUpload/swfupload.swf",
			button_image_url : '../css/backend/screen/images/swfupload.png',
			button_width : 61,
			button_height : 22,
			button_placeholder : $('#'+this.prefix+'_thumb_upload_btn')[0],
			debug: false
			})
			.bind('swfuploadLoaded', function(event){})
			.bind('fileQueued', function(event, file){
				$(this).swfupload('startUpload');
			})
			.bind('fileQueueError', function(event, file, errorCode, message){
				if(errorCode == SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED)
					alert(message);
				if(errorCode == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT)
					alert('Fehler: Die Datei ist größer als '+maxImgSize);
				if(errorCode == SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE)
					alert(message);
				if(errorCode == SWFUpload.QUEUE_ERROR.INVALID_FILETYPE)
					alert(message);
			})
			.bind('fileDialogStart', function(event){})
			.bind('fileDialogComplete', function(event, numFilesSelected, numFilesQueued){})
			.bind('uploadStart', function(event, file){
			})
			.bind('uploadProgress', function(event, file, bytesLoaded, bytesTotal){
				handle.progressBarThumb.progressbar('value', (bytesLoaded/bytesTotal)*100);
				if (bytesLoaded == bytesTotal) {
					// open the crop dialog and start the upload since it's queued
					handle.showCropDialog();
				}
			})
			.bind('uploadSuccess', function(event, file, serverData){
				handle.startCrop(file, serverData);
				handle.progressBarThumb.progressbar('value', 0);
			})
			.bind('uploadComplete', function(event, file){})
			.bind('uploadError', function(event, file, errorCode, message){
				if(errorCode == SWFUpload.UPLOAD_ERROR.HTTP_ERROR)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.IO_ERROR)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.SECURITY_ERROR)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.FILE_CANCELLED)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED)
					alert(message);
			});
		if (this.type == 'button') {
			/*
			 * #########################################################################
			 * ############################# Image Upload ##############################
			 * #########################################################################
			 */
			this.progressBarImage = $('#btn_img_upload_progress_bar').progressbar({});
			this.imageUploader = $('#btn_img_upload_container').swfupload({
				upload_url: libPathPHP+"uploadImage.php",
				file_size_limit : maxImgSize,
				file_types : "*.jpg;*.png;*.gif;*.jpeg",
				file_types_description : "Web Image Files",
				file_upload_limit : "0",
				flash_url : libPathJS+"plugins/swfUpload/swfupload.swf",
				button_image_url : '../css/backend/screen/images/swfupload.png',
				button_width : 61,
				button_height : 22,
				button_placeholder : $('#btn_img_upload_btn')[0],
				debug: false,
				post_params: {
					filename : '', 
					folder: '',
					width: 1,
					height: 1
				}
				})
				.bind('swfuploadLoaded', function(event){})
				.bind('fileQueued', function(event, file){
					$(this).swfupload('startUpload');
				})
				.bind('fileQueueError', function(event, file, errorCode, message){
					if(errorCode == SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED)
						alert(message);
					if(errorCode == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT)
						alert('Fehler: Die Datei ist größer als '+maxImgSize);
					if(errorCode == SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE)
						alert(message);
					if(errorCode == SWFUpload.QUEUE_ERROR.INVALID_FILETYPE)
						alert(message);
				})
				.bind('fileDialogStart', function(event){})
				.bind('fileDialogComplete', function(event, numFilesSelected, numFilesQueued){
					$(this).swfupload('setPostParams', {
						filename : getButtons().currentItem().basename, 
						folder: getButtons().currentItem().path,
						width: parseInt($('#btn_content_width').val()),
						height: parseInt($('#btn_content_height').val())
					});
				})
				.bind('uploadStart', function(event, file){})
				.bind('uploadProgress', function(event, file, bytesLoaded, bytesTotal){
					handle.progressBarImage.progressbar('value', (bytesLoaded/bytesTotal)*100);
					if (bytesLoaded == bytesTotal) {
						// open the crop dialog and start the upload since it's queued
						handle.showCropDialog();
					}
				})
				.bind('uploadSuccess', function(event, file, serverData){
					handle.startCrop(file, serverData);
					handle.progressBarImage.progressbar('value', 0);
				})
				.bind('uploadComplete', function(event, file){
				})
				.bind('uploadError', function(event, file, errorCode, message){
					if(errorCode == SWFUpload.UPLOAD_ERROR.HTTP_ERROR)
						alert(message);
					if(errorCode == SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL)
						alert(message);
					if(errorCode == SWFUpload.UPLOAD_ERROR.IO_ERROR)
						alert(message);
					if(errorCode == SWFUpload.UPLOAD_ERROR.SECURITY_ERROR)
						alert(message);
					if(errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED)
						alert(message);
					if(errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED)
						alert(message);
					if(errorCode == SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND)
						alert(message);
					if(errorCode == SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED)
						alert(message);
					if(errorCode == SWFUpload.UPLOAD_ERROR.FILE_CANCELLED)
						alert(message);
					if(errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED)
						alert(message);
				});
			/*
			 * #########################################################################
			 * ############################# Text Editor ###############################
			 * #########################################################################
			 */
				this.textEditor = $('#btn_text').tinymce({
					// Location of TinyMCE script
					script_url : '../lib/js/plugins/tinymce/jscripts/tiny_mce/tiny_mce.js',
		
					// General options
					theme : "advanced",
					plugins : "style,table,save,advhr,advlink,inlinepopups,insertdatetime,preview,searchreplace,contextmenu,paste,fullscreen,visualchars,nonbreaking,xhtmlxtras",
		
					// Theme options
					theme_advanced_buttons1 : "save,|,undo,redo,|,cut,copy,paste,pastetext,pasteword,|,search,replace,|,cleanup,code,|,fullscreen,|,help",
					theme_advanced_buttons2 : "formatselect,fontselect,fontsizeselect,|,bullist,numlist,|,outdent,indent,blockquote",
					theme_advanced_buttons3 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,removeformat,visualaid,|,sub,sup,|,charmap,advhr",
					theme_advanced_buttons4 : "link,unlink,anchor,|,preview,|,forecolor,backcolor,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking",
					theme_advanced_toolbar_location : "top",
					theme_advanced_toolbar_align : "left",
					theme_advanced_statusbar_location : "bottom",
					theme_advanced_resizing : true,
					
					apply_source_formatting : false,
					
					// Example content CSS (should be your site CSS)
					content_css : "../css/frontend/layout.css",
		
					// Drop lists for link/image/media/template dialogs
					template_external_list_url : "lists/template_list.js",
					external_link_list_url : "lists/link_list.js",
					external_image_list_url : "lists/image_list.js",
					media_external_list_url : "lists/media_list.js",
		
					// Replace values for the template plugin
					template_replace_values : {
						username : "Some User",
						staffid : "991234"
					}
				});
		}
	} catch(e) {
		if(debug) alert('Initialization of new ItemContainer failed, missing or wrong parameter! ('+e+')');
	}
};
ItemContainer.prototype.type = null;
ItemContainer.prototype.prefix = null;
ItemContainer.prototype.item_selector = null;
ItemContainer.prototype.position_selector = null;
ItemContainer.prototype.form = null;
ItemContainer.prototype.urlLoad = null;
ItemContainer.prototype.urlSave = null;
ItemContainer.prototype.urlNew = null;
ItemContainer.prototype.urlDelete = null;
ItemContainer.prototype.urlDeleteThumb = null;
ItemContainer.prototype.urlDeleteImage = null;
ItemContainer.prototype.items = null;
ItemContainer.prototype.thumbUploader = null;
ItemContainer.prototype.imageUploader = null;
ItemContainer.prototype.textEditor = null;
ItemContainer.prototype.progressBarThumb = null;
ItemContainer.prototype.progressBarImage = null;

ItemContainer.prototype.getInstance = function() {
	switch(this.type) {
	case 'category':
		return getCategories();
	case 'project':
		return getProjects();
	case 'button':
		return getButtons();
	}
};
ItemContainer.prototype.length = function(){
	if (this.items != null) {
		var i = 0;
		for (key in this.items) {
			i++;
		}
		return i;
	} else {
		return 0;
	}
};
ItemContainer.prototype.currentItem = function(){
	if(this.items[this[0].value] != null) {
		return this.items[this[0].value];
	} else {
		return null;
	}
};
ItemContainer.prototype.prevItem = function(){
	return this.items[this.prevOption().val()];
};
ItemContainer.prototype.nextItem = function(){
	return this.item[this.nextOption().val()];
};
ItemContainer.prototype.currentOption = function(){
	return $(this.item_selector+' option:selected');
};
ItemContainer.prototype.prevOption = function(){
	return $(this.item_selector + ' option:selected').prev();
};
ItemContainer.prototype.nextOption = function(){
	return $(this.item_selector + ' option:selected').next();
};
ItemContainer.prototype.change = function(event) {
	//if (this.currentItem() != null && this.currentItem().id != 0) {
		this.currentItem().select(event);
	//}
};
ItemContainer.prototype.hideErrorMessages = function () {
	$(this.form).hideErrorMessages();
};
ItemContainer.prototype.clearFormElements = function (empty_selector) {
	if(empty_selector) {
		$(this.item_selector).empty();
	}
	$(this.form).clearForm();
};
ItemContainer.prototype.preSelect = function(preSelection, autoSelect){
	//wenn übergeben, preselected item fokussieren
	if (preSelection != null) {
		this[0].selectedIndex = this.items[preSelection].position;
		$(this.item_selector).val($(this.item_selector +
				' option[value="'+preSelection+'"]').val()).focus().change();
	//anderfalls, wenn autoSelect = true, das erste element fokussieren
	} else if (autoSelect) {
		$(this.item_selector).val($(this.item_selector + ' option:first').val())
			.focus().change();
	} else {
		this.clearFormElements(false);
	}
};

ItemContainer.prototype.show = function(preSelection, autoSelect){
	if (this.length() > 0) {
		//die select-box leeren
		$(this.item_selector).empty();
		//falls positions-box vorhanden, diese leeren
		if (this.position_selector != null) {
			$(this.position_selector).empty();
		}
		var i = 0;
		for(key in this.items) {
			//select-box mit optionen füllen 
			$(this.item_selector).append('<option value="'+key+'" >'
					+this.items[key].alias+'</option>'+'\n');
			//optional position-box füllen
			if (this.position_selector != null) {
				$(this.position_selector).append('<option value="'+i+'" >'
						+(i+1)+'</option>'+'\n');
			}
			i++;
		}
		this.preSelect(preSelection, autoSelect);
	} else {
		this.clearFormElements(true);
	}
};
ItemContainer.prototype.fillItems = function(items_temp, preSelection, autoSelect) {
	//index des items im options array des select-elements
	for(key in items_temp) {
		//Die geladenen Objekte erstellen und in items speichern
		switch (this.type) {
		case 'category':
			this.items[key] = new Category(items_temp[key]);
			break;
		case 'project':
			this.items[key] = new Project(items_temp[key]);
			break;
		case 'button':
			this.items[key] = new Button(items_temp[key]);
			break;
		}
	}
	//preface einfügen
	if (this.type == 'category') {
		var preface = {
				type: 'category',
				basename: 'preface',
				path: '/preface/',
				prefix: 'ctg',
				id: 0,
				alias: 'preface',
				label: 'Preface',
				thumb: '',
				thumb_enable: false,
				start_x: 0,
				start_y: 0,
				position: this.length()
		};
		this.items[0] = new Category(preface);
	}
	if (this.length() > 0) {
		this.show(preSelection, autoSelect);
	} else {
		this.clearFormElements(true);
	}
};
/**
 * Lädt Item-Daten aus der Datenbank, instanziiert damit Item-Objekte
 * die im Item-Container-Objekt gespeichert und anschließend angezeigt werden.
 * 
 * @param params 		Parameter Objekt: {prefix, ctg_id und prj_id}
 * @param preSelection	ID des Items das nach dem laden ausgewählt werden soll.
 * @param autoSelect	Automatische auswahl des ersten Items wenn true
 * @return
 */
ItemContainer.prototype.load = function(params, preSelection, autoSelect) {
	this.items = new Object();
	var handle = this;
	$.getJSON(this.urlLoad, params, function(response){
		//wenn Anfrage erfolgreich und items nicht leer
		if(response.result && response.items != null) {
			handle.fillItems(response.items, preSelection, autoSelect);
		} else {
			if(debug) alert('load ' + handle.type + ' failed:\n'
					+ 'error: ' +response.error +"\n"
					+ 'items: ' +response.items +"\n"
					+ 'itemContainer: ' +($(handle.item_selector).length > 0));
		}
	});
};

ItemContainer.prototype.newItem = function() {
	var item = null;
	switch (this.type) {
	case 'category':
		var item = new Category();
		break;
	case 'project':
		var item = new Project();
		break;
	case 'button':
		var item = new Button();
		break;
	}
	if (this.items == null) {
		this.items = new Object();
		this.items[item.id] = item;
	} else {
		this.items[item.id] = item;
	}
	item.position = this.length()-1;
	this.show(item.id, false);
};

/**
 * Saves the current selected item to the database and reloads 
 * all items afterwards.
 * 
 * @return
 */
ItemContainer.prototype.saveItem = function() {
	if (this.currentItem() != null /*&& this.currentItem().id != 0*/) {
		if(this.currentItem().check()){
			if(this.currentItem().assignValues()) {
				var prefix = this.prefix;
				var ctg_id = this.currentItem().category_id;
				var prj_id = this.currentItem().project_id;
				var handle = this;
				if(this.currentItem().id > 0) {
					//existierendes Item updaten
					$.post(this.urlSave,
							{data: this.currentItem().encodeToJSON()},
							function(response) {
								if(response.result) {
									handle.load({prefix: prefix,
										ctg_id: ctg_id,
										prj_id: prj_id},
										response.id, false);
									alert(handle.type+' gespeichert.');
								} else {
									alert('Save '+handle.type+' failed: '+response.error);
								}
							}, 'json');
				} else {
					//neues Item speichern
					$.post(this.urlNew,
							{data: this.currentItem().encodeToJSON()},
							function(response) {
								if(response.result) {
									handle.load({prefix: prefix,
										ctg_id: ctg_id,
										prj_id: prj_id},
										response.id, false);
									alert(handle.type+' gespeichert.');
								} else {
									alert('Save new '+handle.type+' failed: '+response.error);
								}
							}, 'json');
				}
			}
		} else {
			alert("Eines der rot markierten Felder ausfüllen!");
		}
	}
};
/**
 * Setzt das ausgewählte Item aus seinen zuletzt gespeicherten Stand zurück.
 * 
 * @return
 */
ItemContainer.prototype.resetItem = function(){
	if (this.currentItem() != null && this.currentItem().id != 0) {
		this.currentItem().resetItem();
	}
};
/**
 * Löscht das ausgewählte Item.
 * Alle Daten des Items, die Daten der Kind-Items sowie ihre zugehörigen
 * Bild-Dateien werden aus der Datenbank und vom Datenträger gelöscht.
 * 
 * @return
 */
ItemContainer.prototype.deleteItem = function(){
	if (this.currentItem() != null && this.currentItem().id != 0) {
		if(confirm(this.type+' wirklich löschen?')) {
			var prefix = this.prefix;
			var id = this.currentItem().id;
			if(this.type == 'category') {
				var ctg_id = this.currentItem().id;
			} else {
				var ctg_id = this.currentItem().category_id;
			}
			var prj_id = this.currentItem().project_id;
			var path = this.currentItem().path;
			if (this.currentItem().position != null)
				var position = this.currentItem().position;
			else
				var position = null;
			var selectAfter = null;
			var nextOption = $(this.nextOption()).val();
			if (nextOption != null) {
				var selectAfter = nextOption;
			} else {
				var selectAfter = $(this.prevOption()).val();
			}
			var handle = this;
			
			$.getJSON(this.urlDelete, {prefix: prefix, id: id, ctg_id: ctg_id, path: path, position: position}, function(response){
				if(response.result) {
					handle.load({prefix: prefix, ctg_id: ctg_id, prj_id: prj_id}, selectAfter, false);
					var errorString = 'Löschen erfolgreich:\n';
					if(response.result_files) 
						errorString += '- verknüpfte Dateien gelöscht.\n';
					else errorString += '- keine verknüpften Dateien gefunden.\n';
					if(response.result_categories)
						errorString += '- Kategorie gelöscht.\n';
					else errorString += '- keine Kategorie gelöscht.\n';
					if(response.result_projects)
						errorString += '- Projekte gelöscht.\n';
					else errorString += '- keine Projekte gelöscht.\n';
					if(response.result_buttons)
						errorString += '- Buttons gelöscht.\n';
					else errorString += '- keine Buttons gelöscht.\n';
					if(debug) alert(errorString);
				} else {
					var errorString = 'Delete '+handle.type+' failed: '+response.error+'\n';
					if(response.error_files != null) 
						errorString += 'Error while deleting associated files: ' + response.error_files+'\n';
					if(response.error_categories != null)
						errorString += 'Error while deleting categories: ' + response.error_categories+'\n';
					if(response.error_projects != null)
						errorString += 'Error while deleting projects: ' + response.error_projects+'\n';
					if(response.error_buttons != null)
						errorString += 'Error while deleting buttons: ' + response.error_buttons+'\n';
					if(debug) alert(errorString);
				}
			});
		}
	}
};
/**
 * Löscht das Thumbnail des ausgewählten Items.
 * 
 * @return
 */
ItemContainer.prototype.deleteThumb = function(){
	if (this.currentItem() != null && this.currentItem().id != 0) {
		if (this.currentItem().thumb != null && this.currentItem().thumb != '') {
			if(confirm('Thumb wirklich löschen?')) {
				var id = this.currentItem().id;
				var ctg_id = this.currentItem().category_id;
				var prj_id = this.currentItem().project_id;
				var prefix = this.prefix;
				var path = this.currentItem().thumb.replace(siteRoot, '');
				var handle = this;
				if (this.urlDeleteThumb != null) {
					$.getJSON(this.urlDeleteThumb, {prefix: prefix, id: id, path: path}, function(response){
						if(response.result) {
							handle.load({prefix: prefix, ctg_id: ctg_id, prj_id: prj_id}, id, false);
							var errorString = 'Thumbnail gelöscht\n';
							alert(errorString);
						} else {
							var errorString = 'Thumbnail nicht gelöscht: '+response.error+'\n';
							alert(errorString);
						}
					});
				}
			}
		} else {
			alert('Es existiert kein Thumbnail!');
		}
	} else {
	}
};
/**
 * Löscht das Bild des ausgewählten Items.
 * 
 * @return
 */
ItemContainer.prototype.deleteImage = function(){
	if (this.currentItem() != null && this.currentItem().id != 0) {
		if (this.currentItem().img != null && this.currentItem().img != '') {
			if(confirm('Bild wirklich löschen?')) {
				var id = this.currentItem().id;
				var ctg_id = this.currentItem().category_id;
				var prj_id = this.currentItem().project_id;
				var prefix = this.prefix;
				var path = this.currentItem().img.replace(siteRoot, '');
				var handle = this;
				if (this.urlDeleteImage != null) {
					$.getJSON(this.urlDeleteImage, {prefix: prefix, id: id, path: path}, function(response){
						if(response.result) {
							handle.load({prefix: prefix, ctg_id: ctg_id, prj_id: prj_id}, id, false);
							var errorString = 'Bild gelöscht\n';
							alert(errorString);
						} else {
							var errorString = 'Bild nicht gelöscht: '+response.error+'\n';
							alert(errorString);
						}
					});
				}
			}
		} else {
			alert('Es existiert kein Bild!');
		}
	} else {
	}
};
/**
 * Speichert für das ausgewählte Item ein Thumbnail.
 * 
 * @return
 */
ItemContainer.prototype.saveThumb = function() {
	var path = this.currentItem().path;
	var handle = this;
	if($('.jcrop-holder').length > 0) {
		if(tempImagePath != '') {
			$.post(libPathPHP+"saveThumb.php",
					{file: tempImagePath,
					folder: path,
					crop_x: $('#img_crop_x').val(),
					crop_y: $('#img_crop_y').val(),
					crop_w: $('#img_crop_w').val(),
					crop_h: $('#img_crop_h').val()},
					function(response){
						if (response.result) {
							$('#'+handle.prefix+'_thumb_path').val(response.pathname);
							$('#'+handle.prefix+'_thumb').attr('src',
									siteRoot+response.pathname+'?'+Math.floor(Math.random()*1001));
							$('#'+handle.prefix+'_thumb_enable').attr('checked', true);
							handle.saveItem();
						} else {
							alert('Fehler beim Erstellen des Thumbnails: '+response.error);
						}
					},
					"json");
		} else {
			alert('Kein Bild hochgeladen');
		}
	}
};
/**
 * Speichert für das ausgewählte Item ein VorschauBild für das Grid.
 * 
 * @return
 */
ItemContainer.prototype.savePreview = function() {
	var path = this.currentItem().path;
	var handle = this;
	if($('.jcrop-holder').length > 0) {
		if(tempImagePath != '') {
			$.post(libPathPHP+"savePreview.php",
					{file: tempImagePath,
					folder: path,
					image_width: parseInt($('#btn_content_width').val())*80-5,
					image_height: parseInt($('#btn_content_height').val())*80-5,
					crop_x: $('#img_crop_x').val(),
					crop_y: $('#img_crop_y').val(),
					crop_w: $('#img_crop_w').val(),
					crop_h: $('#img_crop_h').val()},
					function(response){
						if (response.result) {
							$('#'+handle.prefix+'_img_path').val(response.filepath);
							$('#'+handle.prefix+'_img').attr('src',
									siteRoot+response.previepath+'?'+Math.floor(Math.random()*1001));
							$('#'+handle.prefix+'_img_enable').attr('checked', true);
							handle.saveItem();
						} else {
							alert('Fehler beim Erstellen der Bildvorschau: '+response.error);
						}
					},
					"json");
		} else {
			alert('Kein Bild hochgeladen');
		}
	}
};
ItemContainer.prototype.paintBtnDummy = function (x, y, width, height) {
	$('#btn_btn_dummy').css({
		width: Math.abs(Math.round(
				73*imgScaleRatioX)),
		height: Math.abs(Math.round(
				73*imgScaleRatioY)),
		marginLeft: Math.abs(Math.round(
				(this.x*80)*imgScaleRatioX)),
		marginTop: Math.abs(Math.round(
				(this.y*80)*imgScaleRatioY))
	}).show();
	$('#btn_content_dummy').css({
		marginLeft: Math.abs(Math.round(
				(this.content_x*80)*imgScaleRatioX)),
		marginTop: Math.abs(Math.round(
				(this.content_y*80)*imgScaleRatioY)),
		width: Math.abs(Math.round(
				(this.content_width*80-7)*imgScaleRatioX)),
		height: Math.abs(Math.round(
				(this.content_height*80-7)*imgScaleRatioY))
	}).show();
};
ItemContainer.prototype.updatePreview = function() {
	if(this.type == 'button') {
		$('#btn_btn_dummy').css({
			width: Math.abs(Math.round(
					73*imgScaleRatioX)),
			height: Math.abs(Math.round(
					73*imgScaleRatioY)),
			marginLeft: Math.abs(Math.round(
					($('#'+this.prefix+'_x').val()*80)*imgScaleRatioX)),
			marginTop: Math.abs(Math.round(
					($('#'+this.prefix+'_y').val()*80)*imgScaleRatioY))
		}).show();
		$('#btn_content_dummy').css({
			marginLeft: Math.abs(Math.round(
					($('#'+this.prefix+'_content_x').val()*80)*imgScaleRatioX)),
			marginTop: Math.abs(Math.round(
					($('#'+this.prefix+'_content_y').val()*80)*imgScaleRatioY)),
			width: Math.abs(Math.round(
					($('#'+this.prefix+'_content_width').val()*80-7)*imgScaleRatioX)),
			height: Math.abs(Math.round(
					($('#'+this.prefix+'_content_height').val()*80-7)*imgScaleRatioY))
		}).show();
		//var marginLeft = Math.abs(Math.round(
		//		($('#'+this.prefix+'_content_x').val()*80)*imgScaleRatioX));
		//var marginTop = Math.abs(Math.round(
		//		($('#'+this.prefix+'_content_y').val()*80)*imgScaleRatioY));
		var width = Math.abs(Math.round(
				($('#'+this.prefix+'_content_width').val()*80-5)*imgScaleRatioX));
		var height = Math.abs(Math.round(
				($('#'+this.prefix+'_content_height').val()*80-7)*imgScaleRatioY));
		$('#'+this.prefix+'_img')
				.attr('width', width)
				.attr('height', height);
				//.css({
				//	marginLeft: marginLeft+'px',
				//	marginTop: marginTop+'px'
				//});*/
	}
};
ItemContainer.prototype.checkAlias = function(newAlias) {
	if (newAlias == '') {
		alert('Bitte einen Alias eingeben!');
		return false;
	}
	for (key in this.items) {
		if (newAlias == this.items[key].alias) {
			alert('Alias existiert bereits! Bitte einen eindeutigen Alias eingeben.');
			return false;
		}
	}
	return true;
};
ItemContainer.prototype.showCropDialog = function() {
	$('#crop_container').addClass('loading');
	resetCrop();
	cropDialog.dialog('open');
	cropDialog.container = this;
};
ItemContainer.prototype.startCrop = function(file, serverData) {
	var response = jQuery.parseJSON(serverData);
	if(response.result){
		$('.swfupload').hide();
		cropDialog.callback = response.callback;
		$('#crop_container').removeClass('loading');
		crop(response, true);
	} else {
		if(debug) alert('Error while uploading image: '+response.response);
	}
};